package com.olah.ws.controller;

import com.olah.common.entity.dto.UtilResponse;
import com.olah.common.entity.po.msg.system.SystemMsg;
import com.olah.common.entity.po.msg.system.SystemMsgType;
import com.olah.common.entity.po.msg.system.SystemJoinProjectMsg;
import com.olah.common.entity.po.ws.dto.core.WebSocketRequest;
import com.olah.common.entity.po.ws.dto.join_project.JoinProjectRequest;
import com.olah.common.entity.po.ws.dto.join_project.JoinProjectResponse;
import com.olah.ws.service.SystemMsgService;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static com.olah.ws.service.WebSocketService.notifySystemMsg;

/**
 * Join Project Controller
 */
@RefreshScope
@RestController
@RequestMapping("/ws/join")
public class JoinProjectController {

    @Resource
    private SystemMsgService systemMsgService;

    /**
     * 加入项目申请
     * @param request 申请
     */
    @PostMapping("/request")
    public UtilResponse<Boolean> joinRequest(@RequestBody WebSocketRequest<JoinProjectRequest> request) {
        SystemJoinProjectMsg<JoinProjectRequest> joinMsg = new SystemJoinProjectMsg<>(request.getSender(), request.getData());
        SystemMsg systemMsg = systemMsgService.newSystemMsg(request.getReceiver().getId(), joinMsg, SystemMsgType.JOIN_PROJECT_REQUEST);
        notifySystemMsg(request.getReceiver().getId(), "你收到一条项目加入申请", systemMsg, "projectJoinRequest");
        return UtilResponse.success("请求发送成功", true);
    }

    /**
     * 审核项目反馈
     * @param response 反馈
     */
    @PostMapping("/response")
    public UtilResponse<Boolean> joinResponse(@RequestBody WebSocketRequest<JoinProjectResponse> response) {
        SystemJoinProjectMsg<JoinProjectResponse> joinMsg = new SystemJoinProjectMsg<>(response.getSender(), response.getData());
        SystemMsg systemMsg = systemMsgService.newSystemMsg(response.getReceiver().getId(), joinMsg, SystemMsgType.JOIN_PROJECT_RESPONSE);
        if (response.getData().getResult()) {
            systemMsgService.joinProject(response.getReceiver().getId(), response.getData().getId());
            notifySystemMsg(response.getReceiver().getId(), response.getSender().getName() + "接受了你的入组申请", systemMsg, "projectJoinResponse");
        } else {
            notifySystemMsg(response.getReceiver().getId(), response.getSender().getName() + "拒绝了你的入组申请", systemMsg, "projectJoinResponse");
        }
        return UtilResponse.success("审核反馈成功", true);
    }

}
